/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.postorder.flow.audit;

import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.oms.order.domain.vo.OmsOrderItemVo;
import com.lxk.oms.order.service.IOmsOrderItemService;
import com.lxk.oms.postorder.domain.bo.OmsPostOrderAddressBo;
import com.lxk.oms.postorder.domain.enums.PostOrderEnums;
import com.lxk.oms.postorder.domain.vo.OmsPostOrderItemVo;
import com.lxk.oms.postorder.domain.vo.OmsPostOrderVo;
import com.lxk.oms.postorder.service.IOmsPostOrderAddressService;
import com.lxk.oms.postorder.service.IOmsPostOrderService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;
import java.util.Map;

/**
 * 审核售后处理
 *
 * @author heyi
 * 2024/10/22
 */
@Slf4j
@AllArgsConstructor
@LiteflowComponent(value = AuditNodeConst.PO_AUDIT_NODE)
public class PoAuditNode extends NodeComponent {
    private final IOmsPostOrderService postOrderService;
    private final IOmsPostOrderAddressService postOrderAddressService;
    private final IOmsOrderItemService omsOrderItemService;

    @Override
    public void process() throws Exception {
        PoAuditContext contextBean = this.getContextBean(PoAuditContext.class);
        OmsPostOrderVo postOrderVo = contextBean.getPostOrderVo();
        Long id = postOrderVo.getId();
        Boolean postOrderStatus = contextBean.getPostOrderStatus();
        // 审核通过，填充商家收货地址
        if (postOrderStatus) {
            Boolean success = postOrderService.updateStatus(id, PostOrderEnums.PostOrderStatus.REVIEW, PostOrderEnums.PostOrderStatus.RETURNED);
            if (!success) {
                log.error("售后订单异常,编号{},状态:{}", postOrderVo.getPostOrderNo(), postOrderVo.getStatus());
                throw new ServiceException("售后订单异常");
            }
            OmsPostOrderAddressBo orderAddressBo = contextBean.getOrderAddressBo();
            orderAddressBo.setPostOrderId(postOrderVo.getId());
            orderAddressBo.setPostOrderSn(postOrderVo.getPostOrderNo());
            orderAddressBo.setType(PostOrderEnums.AddressType.SHOP.getCode());
            orderAddressBo.setMerId(postOrderVo.getMerId());
            postOrderAddressService.insertByBo(orderAddressBo);
        } else {
            // 审核拒绝
            Boolean success = postOrderService.updateStatus(id, PostOrderEnums.PostOrderStatus.REVIEW, PostOrderEnums.PostOrderStatus.FAIL);
            if (!success) {
                log.error("售后审核失败时，售后订单异常,编号{},状态:{}", postOrderVo.getPostOrderNo(), postOrderVo.getStatus());
                throw new ServiceException("审核失败售后订单异常");
            }
            List<OmsOrderItemVo> omsOrderItemVos = contextBean.getOmsOrderItemVos();
            // 回退子订单的可售后数量
            Map<Long, OmsOrderItemVo> orderItemVoMap = omsOrderItemService.convertToMap(omsOrderItemVos);
            List<OmsPostOrderItemVo> postOrderItemVoList = contextBean.getPostOrderItemVoList();
            postOrderItemVoList.forEach(item -> {
                OmsOrderItemBo update = calRollBackOrderItem(item, orderItemVoMap);
                omsOrderItemService.updateByBo(update);
            });
        }

    }

    private OmsOrderItemBo calRollBackOrderItem(OmsPostOrderItemVo item, Map<Long, OmsOrderItemVo> orderItemVoMap) {
        Long orderItemId = item.getOrderItemId();
        Integer count = item.getRefundCount();
        OmsOrderItemVo omsOrderItemVo = orderItemVoMap.get(orderItemId);
        OmsOrderItemBo update = new OmsOrderItemBo();
        update.setId(orderItemId);
        update.setSaleAfterNum(omsOrderItemVo.getSaleAfterNum() + count);
        update.setSaleAfterNumSold(omsOrderItemVo.getSaleAfterNumSold() - count);
        int saleAfterNumSold = update.getSaleAfterNumSold();
        if (saleAfterNumSold == 0) {
            update.setSaleAfterStatus(OrderEnums.SaleAfterStatus.NOT.getCode());
        } else if (saleAfterNumSold > 0 && saleAfterNumSold < omsOrderItemVo.getCount()) {
            update.setSaleAfterStatus(OrderEnums.SaleAfterStatus.PART.getCode());
        } else {
            update.setSaleAfterStatus(OrderEnums.SaleAfterStatus.ALL.getCode());
        }
        return update;
    }
}
